package com.ruoyi.business.utils;

import com.ruoyi.common.exception.UtilException;
import lombok.extern.slf4j.Slf4j;
import org.geotools.kml.KMLConfiguration;
import org.geotools.xsd.PullParser;
import org.opengis.feature.simple.SimpleFeature;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.xml.sax.SAXException;

import javax.xml.stream.XMLStreamException;
import java.io.FileInputStream;
import java.io.IOException;

@Slf4j
public class AnalysisKml {
    public static void main(String[] args) {
        String fileUrl = "/Users/liutao/Downloads/2.kml";
        try (FileInputStream fileInputStream = new FileInputStream(fileUrl)) {
            PullParser parser = new PullParser(new KMLConfiguration(), fileInputStream, SimpleFeature.class);
            SimpleFeature simpleFeature = (SimpleFeature) parser.parse();
            //kml文件声明了坐标系才能获取到，没声明获取就是null
            CoordinateReferenceSystem coordinateReferenceSystem = simpleFeature.getFeatureType().getCoordinateReferenceSystem();
            log.info("解析kml获取坐标系：{}", coordinateReferenceSystem);
            readKml(simpleFeature, parser);
        } catch (XMLStreamException | IOException | SAXException e) {
            throw new UtilException(e.getMessage());
        }
    }

    //递归方式获取每个地块信息
    public static void readKml(SimpleFeature simpleFeature, PullParser parser) throws XMLStreamException, IOException,
            SAXException {
        //读取属性
        AnalysisUtil.readProperty(simpleFeature);
        //获取下一个simpleFeature
        while (simpleFeature != null && simpleFeature.getDefaultGeometry() != null) {
            simpleFeature = (SimpleFeature) parser.parse();
            readKml(simpleFeature, parser);
        }
    }
}
